<script setup>
import baseModel from "@/components/baseModel/baseModel.vue";
import { reactive, ref, watch } from "vue";
import request from "@/common/utils/request";
import { debounce } from "lodash";

const dialog = ref(null);
import utils from "@/common/utils/utils";
import {
  QuestionCircleOutlined,
  DeleteOutlined,
  PlusOutlined,
  CloudUploadOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons-vue";

const emit = defineEmits(["close", "submit"]);

// 素材库
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import { message, Form } from "ant-design-vue";
const useForm = Form.useForm;

// 上传视频要求

// import videRequirementsModal from "./videRequirementsModal.vue";

const state = reactive({
  // url: 'https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/aifile/20241011/H6x2vAreUVcu4Hw3aQ.png?imageView2/2/w/408/h/0',
  selectData: {},
  visible: false,
  extension: "",
  videRequirementsVisible: false,
  // 生成消耗时长
  checked_num: "",
  // 内部弹窗的倒计时关闭时间
  closeTime: 5,
});

// 获取素材
const getMaterial = () => {
  state.extension = informationData.value.video_url.allow_extension
    .map((extension) => "." + extension)
    .join(",");
  state.visible = true;
};

// 判断是否小于x秒
const isLessThanFiveSeconds = (timeStr) => {
  const parts = timeStr.split(":").map(Number);
  const seconds = parts[0] * 60 + parts[1]; // 转换为秒
  return seconds < informationData.value.video_url?.min_video_duration;
};

// 判断是否超过x分钟
const isMoreThan30Minutes = (timeStr) => {
  const parts = timeStr.split(":");
  const minutes = parseInt(parts[0], 10);
  console.log(minutes, "minutesminutes");
  return minutes >= 5; // 如果小时数大于0或者分钟数大于30，则返回true
};

// 判断是否大于限制
const isSizeGreaterThanSize = (sizeStr) => {
  // 移除字符串中的非数字字符
  const sizeNum = parseFloat(sizeStr.replace(/[^0-9.]/g, ""));
  console.log(sizeNum, "sizeNum");

  // 最大的大小
  const maxSize =
    (informationData.value?.video_url?.max_video_size || 0) / (1024 * 1024) ||
    300;
  console.log(maxSize, "maxSize");

  // 判断大小是否超过Size
  return sizeNum > maxSize;
};

const formState = reactive({
  name: "",
  video_url: "",
  type: "ov4",
  uniqueId: ""
});
const rulesRef = reactive({
  name: [
    {
      required: true,
      message: "请输入数字人名称",
    },
  ],
  video_url: [
    {
      required: true,
      message: "请上传视频",
    },
  ],
});
const { resetFields, validate, validateInfos } = useForm(formState, rulesRef);

// 选择素材回调
const closeChooseMaterial = (data) => {
  console.log("data, 选择的视频", data);
  console.log(Object.prototype.toString.call(data), "data类型");
  if (data) {
    if (isSizeGreaterThanSize(data.material_size_text)) {
      message.warn("视频大小不能大于300MB");
      return;
    }
    if (isMoreThan30Minutes(data.material_duration_text)) {
      message.warn("视频长度不能超过5分钟");
      return;
    }
    if (isLessThanFiveSeconds(data.material_duration_text)) {
      message.warn("视频长度不能少于30秒");
      return;
    }
    formState.video_url = data?.material_url;
    if (Array.isArray(data) && data.length) {
      state.selectData = data[0];
    } else if (Object.prototype.toString.call(data) == "[object Object]") {
      state.selectData = data;
    } else {
      message.error("请选择视频");
      return;
    }
  }
  state.visible = false;
};

const timer = ref(null);
// 子弹窗倒计时减少事件
const closeTimeReduce = () => {
  timer.value = setInterval(() => {
    state.closeTime--;
    if (state.closeTime <= 0) {
      closeModalChange();
    }
  }, 1000);
};

// 子弹窗关闭清除数据
const closeModalChange = () => {
  state.videRequirementsVisible = false;
  clearInterval(timer.value);
  state.closeTime != 0 && (state.closeTime = 0);
};

// 打开弹窗
const showModal = () => {
  dialog.value.showModal();
  state.videRequirementsVisible = true;
  state.closeTime = 5;
  closeTimeReduce();
};
const closeModal = () => {
  dialog.value.closeModal();
};

const deleteOutlinedClick = () => {
  formState.video_url = "";
  state.selectData = {};
};

const isCloseChange = () => {
  resetFields();
  state.selectData = {};
};

const isVisibleChange = () => {
  getRequiredInformation();
};

const informationData = ref({});
const getRequiredInformation = () => {
  request.get("/work_ai", "/digital/human/required/information").then((res) => {
    console.log(res.result, "限制");

    informationData.value = res.result;
  });
};

const loading = ref(false);

    const getuniqueId = async () => {
      const res = await request.get("/work_ai", "/user/platform/uniqueId")
      formState.uniqueId = res.uniqueId
    }


const onSubmit = async () => {
  await getuniqueId()
  validate().then(() => {
    loading.value = true;
    request
      .post("/work_ai", "/digital/human/add", formState)
      .then((res) => {
        message.success("保存成功");
        loading.value = false;
        emit("submit");
      })
      .catch((err) => {
        loading.value = false;
      });
  });
};

const debounceonSubmit = debounce(onSubmit, 1000, {
  leading: true,
  trailing: false,
});

// 上传视频要求
const videRequirements = () => {
  state.videRequirementsVisible = true;
};
// 子弹窗关闭事件
const cancelChange = () => {
  closeModalChange();
};

defineExpose({
  showModal,
  closeModal,
});
</script>

<template>
  <div>
    <baseModel
      ref="dialog"
      :contentWidth="'1200px'"
      :maskClosable="false"
      @isClose="isCloseChange"
      @isVisible="isVisibleChange"
    >
      <template #title>
        <span class="is_title">创建您的数字人分身</span>
      </template>
      <template #content>
        <div class="content">
          <a-form :hideRequiredMark="true">
            <div class="bottom_update_video">
              <div class="bottom_update_video_left">
                <a-form-item v-bind="validateInfos.name">
                  <template #label>
                    <div style="font-weight: 600; color: #4d4d4d">
                      {{ informationData.name?.label }}
                    </div>
                  </template>
                  <a-input
                    :placeholder="'请输入' + informationData.name?.label"
                    style="width: 466px"
                    :maxlength="informationData?.name?.max"
                    v-model:value="formState.name"
                  >
                  </a-input>
                  <a-tooltip>
                    <template #title>
                      {{ informationData.name.tip.join("") }}</template
                    >
                    <question-circle-outlined
                      v-if="informationData?.name?.tip"
                      style="margin-left: 5px"
                    />
                  </a-tooltip>
                </a-form-item>
                <div
                  style="margin-bottom: 10px; font-weight: 600; color: #4d4d4d"
                >
                  <!-- {{ informationData.video_url?.label }} -->
                  <!-- <info-circle-outlined
                    style="cursor: pointer"
                    @click="videRequirements"
                  /> -->
                </div>
                <a-form-item v-bind="validateInfos.video_url">
                  <div class="add_material_box">
                    <div
                      class="material_item is_cart"
                      v-if="Object.keys(state.selectData).length"
                    >
                      <DeleteOutlined
                        class="deleteOutlined"
                        @click="deleteOutlinedClick"
                      ></DeleteOutlined>
                      <template v-if="state.selectData?.cover_url">
                        <img :src="state.selectData?.cover_url" alt="" />
                      </template>

                      <template v-else>
                        <video :src="formState.video_url"></video>
                      </template>
                    </div>

                    <div
                      class="add_material_select is_cart"
                      v-else
                      @click="getMaterial"
                    >
                      <cloud-upload-outlined style="font-size: 24px" />
                      <div>点击上传视频文件</div>
                      <div>支持360p~4K，最大300MB</div>
                    </div>

                    <div class="add_mater_btn">
                      <a-button
                        type="primary"
                        @click="debounceonSubmit"
                        :loading="loading"
                      >
                        提交视频训练
                      </a-button>
                    </div>
                  </div>
                </a-form-item>
              </div>
              <div class="bottom_update_video_right">
                <!-- justify="center" -->
                <a-row :wrap="false">
                  <a-col>
                    <h2 class="bottom_update_video_titleTwo">视频要求:</h2>
                    <ul class="tips">
                      <Li
                        v-for="text in informationData?.video_url?.tip"
                        :key="text"
                      >
                        {{ text }}
                      </Li>
                    </ul>
                  </a-col>
                  <a-col :span="12" style="padding-left: 25px">
                    <h2 class="bottom_update_video_titleTwo">免责声明:</h2>
                    <ul class="tips">
                      <Li>请确认您使用的视频已获取其本人或团队授权</Li>
                      <Li>
                        您承诺您上传的视频严格遭守中国的法律法规要求,不涉及黄、赌、毒，及任何形式的政治敏感信息等
                      </Li>
                      <Li>
                        如果您违反上述规定，存在任何违法行为，由此产生的所有法律责任由使用者自行承担
                      </Li>
                    </ul>
                  </a-col>
                </a-row>

                <div
                  style="margin-bottom: 8px; font-weight: bold; color: #4d4d4d"
                >
                  拍摄视频要求
                </div>
                <div>
                  <span class="text-color">1、</span>
                  只有一张人脸出境，不要使用有多人的视频
                </div>
                <div>
                  <span class="text-color">2、</span
                  >人脸在视频中建议人脸宽度占整体画面宽度1/3以上，确保人脸不要太小
                </div>
                <div>
                  <span class="text-color">3、</span
                  >人脸不要出屏幕，确保整张人脸都在屏幕区域内，确保人脸不要太大
                </div>
                <div>
                  <span class="text-color">4、</span
                  >确保人脸面部特征没有被遮挡，并努力让面部轮廓清晰可见
                </div>
                <div
                  style="font-weight: 700; margin: 10px 0 5px; color: #4d4d4d"
                >
                  拍摄不佳示例
                </div>
                <div style="text-align: center">
                  <img
                    src="@/common/image/shotstack/biaoqingganrao.png"
                    class="image"
                  />
                </div>
              </div>
            </div>
          </a-form>
        </div>
      </template>
      <template #footer>
        <div class="bottom">
          <!-- <a-button type="primary" @click="onSubmit" :loading="loading">
            提交视频训练
          </a-button> -->
        </div>
      </template>
    </baseModel>
  </div>

  <!-- 素材库 -->
  <ChooseMaterial
    useType="AIdigitalHuman"
    :isClip="true"
    material_type="video"
    :multiple="true"
    :extension="state.extension"
    :visible="state.visible"
    @close="closeChooseMaterial"
  />

  <!-- 上传视频要求 -->
  <!-- <videRequirementsModal
    :closeTime="state.closeTime"
    :visible="state.videRequirementsVisible"
    @cancel="cancelChange"
  /> -->
</template>

<style lang="less" scoped>
@fontColor: #1c1f23;

.is_title {
  font-size: 16px;
  font-weight: 600;
}

.content {
  display: flex;
  flex-direction: column;
  // height: 666px;
  // overflow: auto;
  // padding-left: 10%;
  // align-items: center;

  .bottom_update_video {
    display: flex;
    width: 100%;
    height: 100%;
    .bottom_update_video_left {
      width: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .bottom_update_video_right {
      width: 50%;
      // min-width: ;
      padding-left: 20px;
      // background-color: skyblue;
    }

    .bottom_update_video_titleOne {
      font-weight: 600;
    }

    .bottom_update_video_titleTwo {
      font-size: 14px;
      font-weight: 600;
      color: #4d4d4d;
    }

    .tips {
      li {
        margin-bottom: 10px;
        font-size: 14px;
      }
    }

    // 添加素材
    .add_material_box {
      .is_cart {
        width: 160px;
        height: 424px;
        background-color: #f1f3f5;
        cursor: pointer;
        border: 1px solid transparent;
        border-radius: 15px;
        overflow: hidden;
      }

      .add_material_select {
        width: 100%;
        height: 424px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 1px;
        transition: all 0.3s;

        &:hover {
          border-color: var(--ss-primary-color-hover);
        }

        .plusOutlined {
          font-size: 22px;
        }
      }

      .material_item {
        position: relative;

        &::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          height: 100%;
          width: 100%;
          transition: all 0.3s;
          background: #00000042;
          opacity: 0;
          z-index: 1;
        }

        &:hover {
          .deleteOutlined {
            opacity: 1;
          }

          &::before {
            opacity: 1;
          }
        }

        img {
          height: 100%;
          width: 100%;
          object-fit: cover;
        }

        video {
          height: 100%;
          width: 100%;
        }

        .deleteOutlined {
          position: absolute;
          font-size: 30px;
          top: 50%;
          left: 50%;
          transition: all 0.3s;
          transform: translate(-50%, -50%);
          opacity: 0;
          z-index: 2;
          color: #fff;

          &:hover {
            color: red;
          }
        }
      }
    }
  }
}

.bottom {
  display: flex;
  justify-content: center;
}

.text-color {
  color: #0952c8;
}
.image {
  width: auto;
  height: 260px;
}

.add_mater_btn {
  margin-top: 50px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
